package cn.ftp;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;

public class MyUtil {

	public static enum Command {
		RETR, STOR, PWD, LIST, CWD, HELP, QUIT, 
		USER, PASS, ACCT, CDUP, SMNT, REIN, PORT, PASV, EPSV, TYPE, STRU,
		STOU, APPE, ALLO, REST, RNFR, RNTO, ABOR, DELE, RMD, MKD,
		NLST, SITE, SYST, STAT, NOOP,
		ERROR
	};
	
	public static String SP = " ";
	public static String CRLF = "\r\n";
	
	public static String defaultIp = "127.0.0.1";
//	public static String defaultIp = "59.66.131.63";
	
//	public static int defaultPort = 21;
	public static int defaultPort = 1481;
	
	private static HashMap<String, Command> opMap = null;
	
	private static void initMap() {
		opMap = new HashMap<String, Command>();
		opMap.put("get", Command.RETR);
		opMap.put("put", Command.STOR);
		opMap.put("pwd", Command.PWD);
		opMap.put("dir", Command.LIST);
		opMap.put("cd", Command.CWD);
		opMap.put("?", Command.HELP);
		opMap.put("quit", Command.QUIT);
	}
	
	public static Command getCommand(String command) {
		if (opMap == null) {
			initMap();
		}
		if (command.contains(SP)) {
			command = command.substring(0, command.indexOf(SP));
		} else {
			command = command.trim();
		}
		if (opMap.containsKey(command)) {
			return opMap.get(command);
		} else {
			return Command.ERROR;
		}
	}

	public static String getInputLine(String instructInfo) {
		if (instructInfo != null) {
			System.out.print(instructInfo);
		}
		InputStreamReader isr = new InputStreamReader(System.in);

		BufferedReader br = new BufferedReader(isr);
		String s = null;
		try {
			s = br.readLine();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
//		System.out.println("Input: \"" + s + "\"");
		return s;
	}

	public static boolean checkDirValid(String dir) {
		File f = new File(dir);
		return (f.exists() && f.isDirectory());
	}
	
	public static int getCode(String line) {
		String code = null;
		if (line.contains(SP)) {
			code = line.substring(0, line.indexOf(SP));
		} else {
			code = line.trim();
		}
//		System.out.println(line.substring(line.indexOf(SP) + 1).trim());
		return Integer.parseInt(code);
	}
	
	public static String getContent(String line) {
		if (line.contains(SP)) {
			return line.substring(line.indexOf(SP) + 1).trim();
		} else {
			return "";
		}
	}
	
}
